<?php
namespace app\agent\controller;

use app\lib\exception\LoginException;
use app\lib\exception\SuccessMessage;
use app\lib\validate\UserLogin;
use think\Controller;
use think\Request;
use app\agent\model\Agent;


class Login extends Controller
{
    public function index() {
        //如果已经登录
        if(session('agentId')) {
            $this->redirect('/agent');
        }

        return view();
    }
    
    //登录
    public function login() {
        (new UserLogin())->goCheck();

        $data = Request::instance()->post();
        $userInfo = Agent::where(array('mobile' => $data['mobile']))->find();

        if (empty($userInfo)) {
            throw new LoginException([
                'msg' => '该账户不存在，联系管理员开通'
            ]);
        }
        if ($userInfo['pwd'] != MD5($data['password'])) {
            throw new LoginException([
                'msg' => '密码不正确'
            ]);
        }
        if($userInfo['status'] == 0) {
            throw new LoginException([
                'msg' => '账号已被禁用，请联系管理员'
            ]);
        }
        if ($userInfo['status'] == 1) {
            session('agentName', $userInfo['name']);
            session('agentMobile', $userInfo['mobile']);
            //更新用户数据
            $this->updateUserLogin($userInfo['id']);
            throw new SuccessMessage([
                'msg' => '登录成功'
            ]);
        }
    }

    //退出
    public function logOut() {
        session('agentName', null);
        session('agentId', null);
        session('agentMobile', null);
        $this->redirect('Login/index');
    }

    //更新用户登录信息
    private function updateUserLogin($id) {
        //保存用户信息和登录凭证
        session('agentId', $id);

        /*$userData = Agent::where(array('id' => $id))->find();

        $data = array();
        if ($userData) {
            $data['login_times'] = $userData['login_times'] + 1;
            $data['last_login_time'] = date("Y-m-d");
            return Admin::where(array('id' => $id))->update($data);
        } else {
            return false;
        }*/
    }
}